package cn.topevery.garden.framework.util;

import cn.topevery.garden.framework.base.MsgParam;
import cn.topevery.garden.framework.base.Template;
import cn.topevery.garden.framework.base.TemplateParam;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class MsgUtils {

    public static boolean sendTemplateMessage(MsgParam param) throws Exception {
        Template tem = new Template();
        //跳转小程序页面路径
        tem.setPage("pages/start/index");//param.getPath()
        //模板消息id
        tem.setTemplate_id("OYQxnycqFOjfh0TGWv18WRtf2iFlPYMktF5Tj9d6UcQ");//param.getTemplateId()
        //推送给用户的openid
        tem.setTouser(param.getOpenid());
        List<TemplateParam> paras = new ArrayList<>();
        Set<String> keys = param.getParams().keySet();
        for (String key : keys) {
            paras.add(new TemplateParam(key, param.getParams().get(key)));
        }
        tem.setData(buildData(paras));
        tem.setAccess_token(WeiXinUtil.getAccessToken().getToken());
        try {
            //进行推送
            if (sendTemplateMsg(tem.getAccess_token(), tem)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static boolean sendTemplateMsg(String token, Template template) {
        boolean flag = false;

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
//        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

        requestUrl = requestUrl.replace("ACCESS_TOKEN", token);
        com.alibaba.fastjson.JSONObject jsonResult = HttpUtils.doPost(requestUrl, com.alibaba.fastjson.JSONObject.toJSONString(template));
        if (jsonResult != null) {
            Integer errorCode = jsonResult.getInteger("errcode");
            String errorMessage = jsonResult.getString("errmsg");
            if (errorCode == 0) {
                flag = true;
                log.info("消息发送成功,参数:" + template.toString());
            } else {
                log.error("模板消息发送失败:" + errorCode + "," + errorMessage);
                flag = false;
            }
        }
        return flag;
    }

    private static Map<String, Object> buildData(List<TemplateParam> paras) {
        Map<String, Object> map = new HashMap<>();
        if (paras != null && !paras.isEmpty()) {
            for (TemplateParam para : paras) {
                map.put(para.getKey(), new HashMap<String, String>() {
                    {
                        put("value", para.getValue());
                    }
                });
            }
        }
        return map;
    }
}
